package cn.factorybox.gateway.controller;

import cn.factorybox.common.entity.Result;
import cn.factorybox.common.utils.IdWorker;
import cn.factorybox.gateway.service.TerminalService;
import cn.factorybox.model.entity.DeviceData;
import cn.factorybox.model.entity.FactoryDeviceData;
import cn.factorybox.model.entity.RfidDeviceData;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author flypig
 * @version 1.0
 * @date 2020-03-11 10:56
 */
@Slf4j
@RestController
@RequestMapping("terminal")
public class TerminalController {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TerminalService terminalService;

    /**
     * 遍历数组中的json，循环接收
     * @param request
     * @return
     */
    @PostMapping("saveJson")
    public Result save(HttpServletRequest request) {

//        DeviceData deviceData = new DeviceData();
//        JSONObject json = new JSONObject();
        List<JSONObject> jsonList = new ArrayList<>();
        BufferedReader br;
        String line = null;

        try {
            br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            log.info(sb.toString());
//            json = JSONObject.parseObject(sb.toString());
            jsonList = JSONArray.parseArray(sb.toString(),JSONObject.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (JSONObject json : jsonList) {
            DeviceData deviceData = new DeviceData();
            log.info("json：{}",json.toString());
            deviceData.setId(idWorker.nextId() + "");
            deviceData.setfSerialNumber(json.getString("fSerialNumber"));
            deviceData.setfTemperature((json.getDouble("fTemperature") == null) ? 0 : json.getDouble("fTemperature"));
            deviceData.setfHumidity((json.getDouble("fHumidity") == null) ? 0 : json.getDouble("fHumidity"));
            deviceData.setfCarbonDioxide((json.getDouble("fCarbonDioxide") == null) ? 0 : json.getDouble("fCarbonDioxide"));
            deviceData.setfTvoc((json.getDouble("fTvoc") == null) ? 0 : json.getDouble("fTvoc"));
            deviceData.setfExhaust((json.getDouble("fExhaust") == null) ? 0 : json.getDouble("fExhaust"));
            deviceData.setfPm((json.getDouble("fPm") == null) ? 0 : json.getDouble("fPm"));
            deviceData.setfPressure((json.getDouble("fPressure") == null) ? 0 : json.getDouble("fPressure"));

            // 模拟测试数据的时间,实际接收时注释掉
//        deviceData.setfCreateTime((json.getDate("fCreateTime") == null)? null : json.getDate("fCreateTime"));

            log.info("接收的数据：{}" , deviceData.toString());

            boolean result = terminalService.save(deviceData);

            if (!result) {
                log.info("result: {}" ,result);
                return Result.error("接收数据失败，查无该设备号");
            }
        }

        return Result.ok("接收数据成功");
    }

    //接收工厂的终端数据
    @PostMapping("saveFactory")
    public Result saveFactoryData(HttpServletRequest request) {

        FactoryDeviceData deviceData = new FactoryDeviceData();
        JSONObject json = new JSONObject();
        BufferedReader br;
        String line = null;

        try {
            br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            json = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        int count = json.size();
        // 更加json中的键值对数量判断设备类型，5或者7（代表传感器的个数）
        if (count == 8) {
            deviceData.setiCount("5");
        } else if (count == 10) {
            deviceData.setiCount("7");
        }
        deviceData.setId(idWorker.nextId() + "");
        deviceData.setDeviceId(json.getString("deviceId"));
        deviceData.setfSerialNumber(json.getString("fSerialNumber"));
        deviceData.setfHumidity((json.getDouble("fHumidity") == null) ? 0 : json.getDouble("fHumidity"));
        deviceData.setfTemperature((json.getDouble("fTemperature") == null) ? 0 : json.getDouble("fTemperature"));
        deviceData.setfCarbonDioxide((json.getDouble("fCarbonDioxide") == null) ? 0 : json.getDouble("fCarbonDioxide"));
        deviceData.setfTvoc((json.getDouble("fTvoc") == null) ? 0 : json.getDouble("fTvoc"));
        deviceData.setfPressure((json.getDouble("fPressure") == null) ? 0 : json.getDouble("fPressure"));
        deviceData.setfO3((json.getDouble("fO3") == null) ? 0 : json.getDouble("fO3"));
        deviceData.setfWind((json.getDouble("fWind") == null) ? 0 : json.getDouble("fWind"));
        deviceData.setfPm((json.getDouble("fPm") == null) ? 0 : json.getDouble("fPm"));

        // 模拟测试数据的时间,实际接收时注释掉
        //deviceData.setfCreateTime((json.getDate("fCreateTime") == null)? null : json.getDate("fCreateTime"));

//        System.out.println("接收的数据：" + deviceData.toString());
        log.info("接收到上位机的数据：{}",deviceData.toString());

        terminalService.saveFactoryData(deviceData);

        return Result.ok("接收数据成功");
    }

    @PostMapping("saveRfid")
    public Result saveRfidJson(HttpServletRequest request) {

        RfidDeviceData deviceData = new RfidDeviceData();
        JSONObject json = new JSONObject();
        BufferedReader br;
        String line = null;

        try {
            br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            json = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        deviceData.setId(idWorker.nextId() + "");
        deviceData.setDeviceID(json.getString("deviceID"));
        deviceData.setStrEPC(json.getString("strEPC"));
        deviceData.setmReadCount((json.getInteger("mReadCount") == null) ? 0 : json.getInteger("mReadCount"));

        // 接收测试数据的时间,实际接收时注释掉
//        deviceData.setfCreateTime((json.getDate("fCreateTime") == null)? null : json.getDate("fCreateTime"));

        log.info("接收的数据：{}", deviceData.toString());

        boolean result = terminalService.saveRfid(deviceData);

        if (!result) {
            log.info("result: {}",result);
            return Result.error("接收数据失败，查无该设备号");
        }

        return Result.ok("接收数据成功");
    }

}
